﻿﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using AD_Project.Models;

namespace AD_Project.Controllers
{
    public class FileController : Controller
    {
        private EpShareEntities _db = new EpShareEntities();
        //
        // GET: /File/

        public ActionResult F()
        {
            return View();
        }

        public ActionResult DownloadReview()
        {
            return View();
        }

        public ActionResult DocReview()
        {
            return View();
        }

        public ActionResult Folder()
        {
            return View();
        }

        public ActionResult FolderInfo()
        {
            return PartialView("_FolderInfo");
        }
        public ActionResult Downloads(string id)
        {
            var fileinfor = _db.Files.Single(file => file.id.Equals(id));

            return View(fileinfor);
        }
        [HttpGet]
        public FileResult Download(string key, string time, string ip)
        {
            if (CheckDownloadKey(key, time))
            {
                string fullPath = "";
                FileResult result;

                fullPath = Path.Combine(Server.MapPath("~/upload"), "anh-nho-em.mp3");
                using (FileStream stream = System.IO.File.OpenRead(fullPath))
                {
                    MemoryStream streamFile = GetFile(fullPath);
                    result = new FileContentResult(streamFile.ToArray(), "audio/mp3");
                    result.FileDownloadName = "[ÉpShare]_" + "anh-nho-em";

                }
                return result;
            }
            else
            {
                return null;
            }
        }

        private MemoryStream GetFile(string fullPath)
        {
            byte[] buffer = new byte[4096];
            MemoryStream streamFile = new MemoryStream();
            using (FileStream fs = System.IO.File.OpenRead(fullPath))
            {
                int sourceBytes;
                do
                {
                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                    streamFile.Write(buffer, 0, sourceBytes);
                } while (sourceBytes > 0);
            }
            return streamFile;
        }

        private bool CheckDownloadKey(string guidString, string downloadTime)
        {
            try
            {
                if (String.Format("{0:dMyyyy}", DateTime.Now).Equals(downloadTime))
                {
                    Guid g = new Guid(guidString);
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}
